package cn.kgc.chlm.service.impl;

import cn.kgc.chlm.dao.OrderDao;
import cn.kgc.chlm.dao.UserDao;
import cn.kgc.chlm.dao.impl.OrderDaoImpl;
import cn.kgc.chlm.dao.impl.UserDaoImpl;
import cn.kgc.chlm.entity.Order;
import cn.kgc.chlm.entity.User;
import cn.kgc.chlm.service.OrderService;
import cn.kgc.chlm.utils.JdbcUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    OrderDao orderDao = new OrderDaoImpl();
    UserDao userDao = new UserDaoImpl();


    @Override
    public List<Order> selectOrderByUserId(User user) {
        return orderDao.selectOrderByUserId(user);
    }

    @Override
    public Order selectOrderById(Integer id) {
        return orderDao.selectOrderById(id);
    }

    @Override
    public int addOrder(Order order, User loginUser) {
        //减去我们登录用户的花费的金额
        loginUser.setCash(loginUser.getCash()-order.getCountPrice());

        Connection conn = JdbcUtil.getConnection();
        //开启事务
        try {
            conn.setAutoCommit(false);
            int n = userDao.updateUser(loginUser);
            //int i = 1/0; //制造异常
            n= orderDao.addOrder(order);
            //提交事务
            conn.commit();
        } catch (SQLException throwables) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public int delOrder(Integer id) {
        return orderDao.delOrder(id);
    }


}
